<#include "/public/macro.html">
<div class="uk-layui-form">
	<form class="layui-form" id="autodisform" action="/apps/contacts/item/config/save.html" method="post">
		<input type="hidden" name="id" value="${contactsItem.id!''}">
		<div class="layui-collapse">
			<div class="layui-colla-item">
				<h2 class="layui-colla-title">回收</h2>
				<div class="layui-colla-content layui-show">
					<div class="layui-form-item">
						<div class="layui-inline" >
							<label class="layui-form-label" >自动回收：</label>
							<div class="layui-input-inline">
								 <input type="checkbox" name="autorecycle"  lay-text="开启|关闭" lay-filter="autorecycle" lay-skin="switch" <#if contactsItem?? && contactsItem.autorecycle>checked</#if>>
							</div>
						</div>
						<div class="layui-inline uckefu-inline" id="recycletimediv" <#if contactsItem?? && !contactsItem.autorecycle>style="display:none;"</#if>>
							<label class="layui-form-label" style="width: 165px;">自动回收周期 （小时）：</label>
							<div class="layui-input-inline">
								<input type="number" name="recycletime" style="width: 80px;" id="recycletime"  <#if contactsItem?? && contactsItem.autorecycle>min="1"</#if> value="<#if contactsItem??>${contactsItem.recycletime!'0'}</#if>" class="layui-input">
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="layui-colla-item">
				<h2 class="layui-colla-title">分配</h2>
				<div class="layui-colla-content layui-show">
					<div class="layui-form-item">
						<div class="layui-inline">
							<label class="layui-form-label">自动分配：</label>
							<div class="layui-input-inline">
								<input type="checkbox" lay-filter="autodis" name="autodis" lay-text="开启|关闭" lay-skin="switch" <#if contactsItem?? && contactsItem.autodis>checked</#if>>
							</div>
						</div>
					</div>
					<div class="layui-form-item" id="expressdiv" <#if contactsItem?? && !contactsItem.autodis> style="display: none;"</#if>>
						<div class="layui-inline">
							<label class="layui-form-label"><i class="layui-icon">&#xe61f;</i>添加流转：</label>
							<div class="layui-input-inline" style="position: relative;">
								<input type="hidden" id="parentid" name="salestatus" value="<#if currsaleStatus??>${currsaleStatus.id}<#else>0</#if>">
								<input type="text" name="parentname" id="parentname" required value="<#if currsaleStatus??>${currsaleStatus.name}<#elseif area??>${area.name!''}<#else>分类总揽</#if>" style="width: 220px;" lay-verify="required" autocomplete="off" readOnly="readonly" onClick="showMenu();"
									class="layui-input">
								<i class="layui-icon" style="position: absolute;right: -23px;top: 6px;font-size: 25px;${systemConfig.color!'color:#0096C4;'}" onClick="showMenu()">&#xe631;</i>
								<div id="menuContent" style="display:none; position: absolute;z-index:10000;width: 218px;height: 190px;" class="ukefu-ztree">
									<ul id="saleStatusTypeTree" class="ztree" style="width:208px;height: 180px;"></ul>
								</div>
							</div>
							<div class="layui-input-inline" style="margin-left: 23px;width: 80px;">
								<select name="distype" id="distype" lay-filter="distype">
									<option value="user">用户</option>
									<option value="organ">部门</option>
									<option value="free">释放</option>
								</select>
							</div>
							<!-- <div class="layui-input-inline" id="distarget" style="margin-left: -7px;">
								<select name="distarget" >
									<#if userList?? && userList?size gt 0>
										<#list userList as userr><option value="${userr.id}">${userr.username!''}(${userr.uname!''})</option></#list>
									</#if>
								</select>
							</div> -->
							<div class="layui-input-inline" id="distarget" lay-filter="distarget" style="margin-left: -7px;">
							</div>
							<div class="layui-input-inline" id="disorgan" style="margin-left: -7px;display: none;">
								<div class="layui-inline">
									<div class="layui-input-inline" style="position: relative;">
										<input type="text" name="parentname" id="parentnameorgan" required value="<#if organ??>${organ.name}<#elseif area??>${area.name!''}<#else>组织机构</#if>" lay-verify="required" autocomplete="off" readOnly="readonly" onClick="showMenuorgan();"
											class="layui-input">
										<i class="layui-icon" style="position: absolute;right: 3px;top: 6px;font-size: 25px;${systemConfig.color!'color:#0096C4;'}" onClick="showMenuorgan()">&#xe631;</i>
										<div id="menuContentorgan" style="display:none; position: absolute;z-index:10000;width: 218px;height: 190px;" class="ukefu-ztree">
											<ul id="organTree" class="ztree" style="width:208px;height: 180px;"></ul>
										</div>
									</div>
								</div>
							</div>
							<div class="layui-input-inline" id="qualitydiv" style="margin-left: -7px;width: 130px;">
							      <input type="checkbox" name="qualitycheck" id="qualitycheck" value="1" title="转质检" lay-filter="qualitycheck">
							      <input type="hidden" name="quality" id="quality" value="0">
							</div>
							<div class="layui-input-inline" style="margin-left: -7px;width: 43px;">
								<a href="javascript:void(0)" id="addbtn" class="layui-btn" style="padding: 0;width: 60px;"><i class="layui-icon" style="font-size: 30px;margin: 0;">&#xe61f;</i></a>
							</div>
							<div class="layui-input-inline" id="usertip" style="margin-left: 12px;margin-top: 2px;">
								<font color="red">*（该项目下有权限的用户）</font>
							</div>
						</div>
					</div>
					<div class="layui-form-item" id="expresslist" <#if contactsItem?? && !contactsItem.autodis> style="display: none;"</#if>>
							<div class="row" style="padding:5px;">
							<div class="col-lg-12">
								<table class="layui-table" lay-skin="line">
									<thead>
										<tr class="design-sortable-tr">
											<th>状态</th>
											<th>流转</th>
											<th>对象</th>
											<th>转质检</th>
											<th>操作</th>
										</tr>
									</thead>
									
									<tbody id="distbody">
										<#if itemExpressList?? && itemExpressList?size gt 0>
											<#list itemExpressList as itemExpress>
												<#assign tdid=.now?date>
												<tr class="tdHasContorllor design-dropable-td">
												<input type="hidden" name="status" class="status_${itemExpress.status!''}" value="${itemExpress.status!''}">
												<td width="100">
												 <#if saleStatusList?? && saleStatusList?size gt 0>
	    											<#list saleStatusList as saleStatus>
	    												<#if saleStatus.id==itemExpress.status>${saleStatus.name!''}</#if>
	    											</#list>
	    										</#if>
												</td>
												<input type="hidden" name="distypes" value="${itemExpress.distype!''}">
												<td width="100"><#if itemExpress.distype=='user'>用户<#elseif itemExpress.distype=='organ'>部门<#else>释放</#if></td>
												<td>
													<#assign targetnameStr="">
													<#if itemExpress.targetid?? && itemExpress.targetid?size gt 0>
														<#list itemExpress.targetid as ids>
															<#if ids_index gt 0><#assign targetStr=targetStr+"，"+ids><#else><#assign targetStr=ids></#if>
															<#if userList?? && userList?size gt 0>
																<#list userList as userr>
																	<#if userr.id==ids>
																		<#if ids_index gt 0><#assign targetnameStr=targetnameStr+","+userr.username+"("+userr.uname+")"><#else><#assign targetnameStr=userr.username+"("+userr.uname+")"></#if>
																	</#if>
																</#list>
															</#if>
															<#if organList?? && organList?size gt 0>
																<#list organList as organ>
																	<#if organ.id==ids>
																		<#if ids_index gt 0><#assign targetnameStr=targetnameStr+","+organ.name><#else><#assign targetnameStr=organ.name></#if>
																	</#if>
																</#list>
															</#if>
														</#list>
													</#if>
													${targetnameStr}
												</td>
												<input type="hidden" name="targetids" value="${targetStr}">
												<td><#if itemExpress.quality>是</#if></td>
												<input type="hidden" name="qualitys" value="${itemExpress.quality?c}">
												<td style="white-space:nowrap;width:1%;" nowrap="nowrap"><a href="javascript:void(0)" onclick="$(this).parent().parent().remove();"><i class="layui-icon" style="color:red;">ဆ</i>删除</a></td>
												</tr>
											</#list>
										</#if>
									</tbody>
								</table>
							</div> 	   
						</div>
					</div>
				</div>
			</div>
		</div>

		<div class="layui-form-button">
			<div class="layui-button-block">
				<button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
				<button type="reset" class="layui-btn layui-btn-primary">重置</button>
			</div>
		</div>
	</form>
</div>

<script>
	//Demo
	layui.use('form', function() {
		var form = layui.form;
		form.render(); //更新全部
		form.on('switch(autorecycle)', function(data){
			  if(data.elem.checked){
				  $("#recycletimediv").show();
				  $("#recycletime").attr("min",1);
			  }else{
				  $("#recycletimediv").hide();
				  $("#recycletime").removeAttr("min");
			  }
		}); 
		form.on('switch(autodis)', function(data){
			  if(data.elem.checked){
				  $("#expressdiv").show();
				  $("#expresslist").show();
			  }else{
				  $("#expressdiv").hide();
				  $("#expresslist").hide();
			  }
		}); 
		form.on('select(distype)', function(data){
			 if(data.value=='user'){
				 $("#distarget").show();
				 $("#disorgan").hide();
				 $("#usertip").show();
				 $("#qualitydiv").show();
			 }else if(data.value=='organ'){
				 $("#distarget").hide();
				 $("#disorgan").show();
				 $("#usertip").hide();
				 $("#qualitydiv").show();
			 }else{
				 $("#disorgan").hide();
				 $("#distarget").hide();
				 $("#usertip").hide();
				 $("#qualitydiv").hide();
			 }
		});
		form.on('checkbox(qualitycheck)', function(data){
				if(data.elem.checked){
					$("#quality").val("1");
				}else{
					$("#quality").val("0");
				}
		});  
		
	});
	layui.use('element', function(){
		var element = layui.element;
	});
	
	layui.config({
	      base: '/js/'
	    }).use(['selectPlus', 'jquery'], function () {
	      var $ = layui.$,
	        selectPlus = layui.selectPlus;
	      // 多选
	      selectPlus.render({
	        el: '#distarget',
	        data: [<#if userList?? && userList?size gt 0>
					<#list userList as userr>
					<#if userr_index!=0>,</#if>{
			          "name": "${userr.username!''}(${userr.uname!''})",
			          "id": "${userr.id!''}"
			        }
				</#list>
			</#if>],
	        valueName: "name",
	        values: ['bootstrap', 'element'],
	        valueSeparator: " --- "
	      });
	      selectPlus.on('selectPlus(distarget)', function(obj){  
	    	// 多选时
	    	  usernames = [];
	    	  userids = [];
	    	  var ids=[];
	          var nodes = obj.checkedData;
	          $(".uk_userids").remove();
	          for(var i=0;i<nodes.length;i++)
	           {
	               ids.push(nodes[i].id);
	               usernames.push(nodes[i].name);
	               $("#autodisform").append("<input type='hidden' class='uk_userids' name='userids' id='userids_"+nodes[i].id+"' value='"+nodes[i].id+"' >");
	           }
	          userids = ids;
	          /* $("#userids").attr("value", ids); */
	    	});
	    })
	    
	    $('#addbtn').on("click" , function(){
	    	if($("#parentid").val()!='' && $("#parentid").val()!="0" && $("#parentid").val()!=null && ((usernames!=null && usernames.length > 0) || (organnames!=null && organnames.length > 0) || $("#distype").val()=='free')){
		    	var addstr = "";
		    	var idstr= "td_"+new Date().getTime().toString();
		    	var value="";
		    	addstr += "<tr class='tdHasContorllor design-dropable-td' id='"+idstr+"'>" ;
		    	addstr += "<input type='hidden' name='status' class='status_"+$("#parentid").val()+"' value='"+$("#parentid").val()+"'>" ;
		    	addstr += "<td width='100'>"+$("#parentname").val()+"</td>" ;
		    	if($("#distype").val()=='free'){
		    		addstr += "<input type='hidden' name='distypes' value='free'>" ;
		    		addstr += "<td width='100'>释放</td>" ;
		    		addstr += "<td></td>" ;
		    	}
		    	if($("#distype").val()=='user'){
		    		addstr += "<input type='hidden' name='distypes' value='user'>" ;
		    		addstr += "<td width='100'>用户</td>" ;
		    	}
		    	if($("#distype").val()=='organ'){
		    		addstr += "<input type='hidden' name='distypes' value='organ'>" ;
		    		addstr += "<td width='100'>部门</td>" ;
		    	}
		    	if($("#distype").val()=='user' &&  usernames!=null && usernames.length > 0){
			    	addstr += "<td>"+usernames.toString()+"</td>" ;
			    	value=userids.toString().replace(new RegExp(",",'g'),"，");
		    	}
		    	if($("#distype").val()=='organ' && organnames!=null && organnames.length > 0){
		    		addstr += "<td>"+organnames.toString()+"</td>" ;
		    		value=organids.toString().replace(new RegExp(",",'g'),"，");
		    	}
		    	addstr += "<input type='hidden' name='targetids' value='"+value+"'>" ;
		    	var qualityis="是";
		    	var qualityval="true";
		    	if($("#quality").val()=="0"){
		    		qualityis="";
		    		qualityval="false";
		    	}
		    	addstr += "<td width='100'>"+qualityis+"</td>" ;
		    	addstr += "<input type='hidden' name='qualitys' value='"+qualityval+"'>" ;
		    	addstr += "<td style='white-space:nowrap;width:1%;' nowrap='nowrap'>";
		    	addstr += "<a href='javascript:void(0)' onclick='$(\"#"+idstr+"\").remove();'>";
		    	addstr += "<i class='layui-icon' style='color:red;'>&#x1006;</i>删除</a></td>";
		    	addstr += "</tr>" ;
		    	$("#distbody").append(addstr);
	    	}
	    	
	    	/* alert("userids:"+userids);
	    	alert("usernames:"+usernames);
	    	alert("organids:"+organids);
	    	alert("organnames:"+organnames); */
		})
</script>
<SCRIPT type="text/javascript">
	var userids;
	var usernames=[];
	var setting = {
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			onClick: onClick,
			beforeClick: beforeClick
		}
	};
	
	function beforeClick(treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("saleStatusTypeTree")
		nodes = zTree.getSelectedNodes();
		var allow = true , lastnode ;
		for (var i=0, l=nodes.length; i<l; i++) {
			lastnode = nodes[i].type ;
			if(nodes[i].organ && (nodes.length >= 1 && (event.ctrlKey || event.shiftKey))){
				allow = false ; break ;
			}
		}
		if(lastnode != treeNode.type && (event.ctrlKey || event.shiftKey)){
			allow = false ;
		}
		
		if (allow == false) {
			top.layer.alert("组织机构不能点选多个上级机构，也不能同时选择地区和机构", {icon: 3});
			return false;
		} else {
			return true;
			
		}
	}
	
	function onClick(e, treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("saleStatusTypeTree"),
		nodes = zTree.getSelectedNodes(),
		v = "" , value = "";
		nodes.sort(function compare(a,b){return a.id-b.id;});
		for (var i=0, l=nodes.length; i<l; i++) {
			v += nodes[i].name + ",";
			if(value != ""){
				value = value + "," ;
			}
			value = nodes[i].id ;
		}
		if (v.length > 0 ) v = v.substring(0, v.length-1);
		if(treeNode.type == "saleStatus"){
			$("#parentname").attr("value", v);
			$("#parentid").attr("value", value);
		}
		if (!event.ctrlKey && !event.shiftKey && treeNode.type == "saleStatus") {
			hideMenu() ;
		}
		/* loadURL("/apps/contacts/reservation/salestatuslist.html?id="+treeNode.id,"#salestatus"); */
	}


	var zNodes =[
	    { id:'0', pId:'00', name:"分类总揽", open:true , saleStatusTypeParent : true, type : "saleStatusTypeParent"}
	    <#if saleStatusTypeList??>
	    <#list saleStatusTypeList as saleStatus>
	    <#if saleStatus.activityid?? && statusCode?? &&  saleStatus.activityid == statusCode>
	    ,{ id:'${saleStatus.id!''}', pId:'${saleStatus.parentid!'0'}', name:"${saleStatus.name!''}", open:false }
	    </#if>
	    </#list>
	    </#if>
	    <#if saleStatusList?? >
	    <#list saleStatusList as saleStatus>
	    ,{ id:'${saleStatus.id!''}', pId:'${saleStatus.cate!'0'}', name:"${saleStatus.name!''}" ,  icon:"/images/dept.png", type : "saleStatus", saleStatus : true}
	    </#list>
	    </#if>
	];
	$(document).ready(function(){
		var ztree = $.fn.zTree.init($("#saleStatusTypeTree"), setting, zNodes);
		<#if currsaleStatus??>
		var node = ztree.getNodeByParam('id', '${currsaleStatus.id!''}');//获取id为1的点
		ztree.selectNode(node);//选择点  
		</#if>
		/* <#if area??>
		var node = ztree.getNodeByParam('id', '${area.id!''}');//获取id为1的点
		ztree.selectNode(node);//选择点  
		</#if> */
	});
	function showMenu() {
		$("#menuContent").css({left:"0px", top:"38px"}).show();

		$("body").bind("mousedown", onBodyDown);
	}
	function hideMenu() {
		$("#menuContent").hide();
		$("body").unbind("mousedown", onBodyDown);
	}
	function onBodyDown(event) {
		if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
			hideMenu();
		}
	}

</SCRIPT>
<SCRIPT type="text/javascript">
	var organids;
	var organnames=[];
	var setting = {
		check: {
			enable: true,
			chkStyle: "checkbox",
			chkboxType: { "Y": "", "N": "" }
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			onCheck: findChecked
		}
	};
	function zTreeOnCheck(event, treeId, treeNode) {
	    alert(treeNode.id + ", " + treeNode.name + "," + treeNode.checked);
	};
	
	function findChecked() {
		organnames = [];
		organids = [];
        var treeObj = $.fn.zTree.getZTreeObj("organTree");
        var ids=[];
        var nodes = treeObj.getCheckedNodes(true);
        $(".uk_organids").remove();
        for(var i=0;i<nodes.length;i++)
         {
             ids.push(nodes[i].id);
             organnames.push(nodes[i].name);
             $("#autodisform").append("<input type='hidden' class='uk_organids' name='organids' id='organids_"+nodes[i].id+"' value='"+nodes[i].id+"' >");
         }
        organids = ids;
        /* $("#organids").attr("value", ids); */
    }

	var zNodes =[
	    { id:'0', pId:'00', name:"组织机构", open:true , organ : true, type : "organ"}
	    <#if organList??>
	    <#list organList as organ>
	    ,{ id:'${organ.id!''}', pId:'${organ.parent!'0'}', name:"${organ.name!''}", open:true , organ : true , type : "organ",  icon:"/images/dept.png" }
	    </#list>
	    </#if>
	];
	$(document).ready(function(){
		var ztree = $.fn.zTree.init($("#organTree"), setting, zNodes);
		<#if organ??>
		var node = ztree.getNodeByParam('id', '${organ.id!''}');//获取id为1的点
		ztree.selectNode(node);//选择点  
		</#if>
		<#if area??>
		var node = ztree.getNodeByParam('id', '${area.id!''}');//获取id为1的点
		ztree.selectNode(node);//选择点  
		</#if>
	});
	function showMenuorgan() {
		$("#menuContentorgan").css({left:"0px", top:"38px"}).show();

		$("body").bind("mousedown", onBodyDownorgan);
	}
	function hideMenuorgan() {
		$("#menuContentorgan").hide();
		$("body").unbind("mousedown", onBodyDownorgan);
	}
	function onBodyDownorgan(event) {
		if (!(event.target.id == "menuBtn" || event.target.id == "menuContentorgan" || $(event.target).parents("#menuContentorgan").length>0)) {
			hideMenuorgan();
		}
	}

</SCRIPT>